/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.ejb.EJB;
import javax.print.attribute.standard.Sides;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import jsonHelper.SimpleUniverse;
import service.MumuUser;
import service.MumuUserFacadeREST;
import service.Universe;
import service.UniverseFacadeREST;
import session.UserData;

/**
 *
 * @author andrew
 */
@WebServlet(name = "ControllerServlet", urlPatterns = {"/ControllerServlet"})
public class ControllerServlet extends HttpServlet {

    //private int idUser = 1;
    //private String email = "andrea@gmail.com";
    @EJB
    private MumuUserFacadeREST userMumuManager;
    @EJB
    private UniverseFacadeREST universeManager;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        String email = request.getParameter("username");
        String password = request.getParameter("password");


        password = getMD5(password);

        MumuUser utente = new MumuUser();

        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        //UserData userData = (UserData) session.getAttribute("userData");
        System.out.println("ControllerServlet");

        try {

            /**
             * Controllo che non sia gia loggato con un account, in caso faccio un redirect alla propria pagina
             */
            if (session.getAttribute("userData") != null && session.getAttribute("universeList") != null) {
                System.out.println("Utente e lista già loggati");
                UserData currentUserData = (UserData) session.getAttribute("userData");
                utente = userMumuManager.find(currentUserData.getIDUser());
                checkPrivsAndRedirect(utente, request, response);
            } else {

                List utentiInDb = userMumuManager.findAll();

                int idUser = -1;

                //cerco id dell'utente
                Iterator iteratorUtentiInDb = utentiInDb.iterator();
                while (iteratorUtentiInDb.hasNext()) {
                    MumuUser tempUser = (MumuUser) iteratorUtentiInDb.next();
                    if ((tempUser.getMail().equals(email)) && (tempUser.getPassword().equals(password))) {
                        System.out.println("Utente "+tempUser.getNameSurname()+" trovato");
                        idUser = tempUser.getIdUser();
                    }
                }

                utente = userMumuManager.find(idUser);

                if ((idUser != -1) && (utente.getIsValidated())) {

                    Collection<Universe> collUniverse = universeManager.findAll();

                    ArrayList<SimpleUniverse> collUniverseToView = new ArrayList<SimpleUniverse>();
                    int validated;
                    Iterator itCollUniverse = collUniverse.iterator();
                    while (itCollUniverse.hasNext()) {
                        Universe u = (Universe) itCollUniverse.next();
                        Collection<MumuUser> collUser = u.getMumuUserCollection();
                        Iterator itCollUser = collUser.iterator();
                        while (itCollUser.hasNext()) {
                            MumuUser m = (MumuUser) itCollUser.next();
                            if (m.getIdUser() == idUser) {
                                String avatarPath = "";
                                if (!utente.getIsAdministrator()){
                                    avatarPath = getAvatarPath(u.getIdUniverse(), request);
                                }
                                validated = u.getIsValidated()? 1 : 0;
                                SimpleUniverse su = new SimpleUniverse(u.getIdUniverse(), u.getName(), u.getDescription(),avatarPath, u.getIsReady(), validated);
                                collUniverseToView.add(su);
                                break;
                            }
                        }
                    }



                    session.setAttribute("userData", new UserData(idUser, email, utente.getNameSurname()));
                    session.setAttribute("logged", "logged");

                    checkPrivsAndRedirect(utente, request, response, collUniverseToView);


                } else {
                    response.sendRedirect("/home.jsp?error=1");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("Error");
            out.close();
        }


    }

    private void checkPrivsAndRedirect(MumuUser utente, HttpServletRequest request, HttpServletResponse response, ArrayList<SimpleUniverse> universeList)
            throws Exception {
        HttpSession session = request.getSession();
        if (utente.getIsAdministrator()) {

            String validatingName = request.getParameter("n");
            String validatingEmail = request.getParameter("e");
            String role = request.getParameter("r");
            System.out.println("L'utente è amministratore");
            if (validatingName != null && !validatingName.equals("") && validatingEmail != null || !validatingEmail.equals("")) {
                session.setAttribute("validatingName", validatingName);
                session.setAttribute("validatingEmail", validatingEmail);
                System.out.println("Sta validando "+validatingName);
                //session.setAttribute("email", email);
//                        session.setAttribute("password", password);
                session.setAttribute("role", role);
                // validazione
                response.sendRedirect("/GrantAccessServlet");
            } else {
                System.out.println("Amministratore riconosciuto "+utente.getNameSurname());
                session.setAttribute("currentUser", utente.getIdUser());
                response.sendRedirect("/admin.jsp");
            }

        } else {
            session.setAttribute("universeList", universeList);
            response.sendRedirect("/maker.jsp");
        }
    }

    private void checkPrivsAndRedirect(MumuUser utente, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        if (utente.getIsAdministrator()) {
            response.sendRedirect("/admin.jsp");
        } else {
            response.sendRedirect("/maker.jsp");
        }
    }

    private static String getMD5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            BigInteger number = new BigInteger(1, messageDigest);
            String hashtext = number.toString(16);
            // Now we need to zero pad it if you actually want the full 32 chars.
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }
            return hashtext;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
//        // check if session is expired
//        HttpSession session = request.getSession(false);// don't create if it doesn't exist
//        if(session != null && !session.isNew()) {         
//            processRequest(request, response);
//        } else {
//            response.sendRedirect("/home.jsp");
//        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);

//        // check if session is expired
//        HttpSession session = request.getSession(false);// don't create if it doesn't exist
//        if(session != null && !session.isNew()) {         
//            processRequest(request, response);
//        } else {
//            response.sendRedirect("/home.jsp");
//        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private String getAvatarPath(int idUniverse, HttpServletRequest request) {
        String avatarPath = request.getServletContext().getRealPath("/")+"Universes/" + idUniverse + "/";
        File f = new File(avatarPath);
        
        String[] files = f.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.startsWith("avatar-");
            }
        });
        if(files != null && files.length > 0){
            return "Universes/" + idUniverse + "/" + files[0];
        }
        
        return "img/no-avatar.png";
    }
}
